const util=require('../../utils/util')
import { $wuxBackdrop } from '../../components/lib/index'
// var tmpimages=[];//图片数组路径
Page({
  data: {
    locks:0,
    show:false,

    formats: {},
    readOnly: false,
    placeholder: '分享你的护肤小妙招吧！',
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,

    tempimageid: 1,
    imageid: 1,
    image:[
      // {
      //   imageid:0,
      //   imageurl:'null'
      // }
    ],
    result:[]//图片上传成功后的url数组
  },
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  onLoad() {
    const platform = wx.getSystemInfoSync().platform
    this.$wuxBackdrop = $wuxBackdrop()
    const isIOS = platform === 'ios'
    this.setData({ isIOS})
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)
    })

  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const { windowHeight, platform } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight-60) : (windowHeight-80)
    this.setData({ editorHeight, keyboardHeight })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const { statusBarHeight, platform } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    let app=getApp()
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context //必备初始化语句
      let article=getApp().globalData.article;
      if(article){
        that.editorCtx.setContents({
          // html:article.html,
          // text:article.text,
          delta:article.delta,
          fail:res=>{
            console.log(res)
          }
        })
      }
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  undo(){
    this.editorCtx.undo()
  }
  ,
  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({ formats })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    let that=this;
    this.editorCtx.clear({
      success: function (res) {
        // html='<p><br></p>';
        // text='\r';
        // imagesTempPath=[];
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {
    const that = this
    var max=1//3
    wx.chooseImage({
      count: max,
      success: function (res) {
        let tmpId=that.data.tempimageid
        // console.log(res.tempFilePaths)
        var i = 0
        // for(; i < res.tempFilePaths.length ; i++){
          that.editorCtx.insertImage({
            src: res.tempFilePaths[i], //插入图片临时文件地址
            data: {
              id: tmpId, //临时图片id
            },
            width: '100%',
            success: function () {
              that.data.image.push({id:tmpId,url:res.tempFilePaths[i]})
                // imagesTempPath.push(res.tempFilePaths[i]);//追加到图片数组中
              //   tmpimages.push({id:tmpid,url:res.tempFilePaths[i],success:function(){
              //    tmpid+=1//临时图片id加1
              //  }})
                // console.log('insert image success '+(imagesTempPath.length-1)+":"+res.tempFilePaths[i])
                that.data.tempimageid=tmpId+1;
                console.log(tmpId+" "+res.tempFilePaths[i]);
            }
          })
        // }
      }
    })
  }
  ,
  /*提交*/
  submit: function(){
    let app=getApp()
  //   if(!app.globalData.hasUserInfo){wx.showToast({
  //     icon:'none',
  //     title: '请先登录后进行操作',
  //     duration:2000
  //   })
  //   return;
  // }
    let that=this; 
    var time= util.formatTime(new Date());
    var visible=true;//可见性
    let title='';
    let subTitle='';
    // that.insertDate();
    that.editorCtx.getContents({
       success:async function(res){ //async await 问题
        // html = res.html;
        // text = res.text;
        if(!res.text.replace(/\s+/g, '').length ==0 ){ //&&!res.text.replace(/\s+/g, '\r') if (res.html !== constTxt) {
          // var flag=0;
          // console.log("检测到输入内容" ) //+ res.text
          // console.log(res.delta);

          //替换res.delta中的图片url

          let images=that.data.image;
          console.log(images.length+"张临时图片")
          var length = res.delta.ops.length;
          wx.showLoading({
            title: '正在上传',
          })
          for (var i = 0; i < length; i++) {
            if(res.delta.ops[i].attributes){//筛选出里面的图片
              let imageId=that.data.imageid;  
              var _id =parseInt(res.delta.ops[i].attributes['data-custom'].trim().slice(3));//取出临时图片的id
              for (var j = 0; j < images.length; j++){      
                if (_id === images[j].id){			//与实际图片地址的id比较，并替换图片地址
                    // tmpimages[j].url=await util.uploadFile('image',tmpimages[j].url,'articlePictures/'+ (new Date().getTime())+'.png',{
                    // id: imageId
                    // });//设置图片id,需与临时图片id一致，所以初始化赋值时两个均为0即可
                    res.delta.ops[i].insert.image = await util.uploadFile('image',images[j].url,'articlePictures/'+ (new Date().getTime())+'.png',{
                      id: imageId
                    });
                    that.data.result.push(res.delta.ops[i].insert.image);
                    console.log(_id+" "+that.data.result[imageId-1])
                    that.data.imageid=imageId+1;
                  break;
                }                          
              }        
            }
          }
          // console.log((that.data.imageid-1)+"张实际图片")
          console.log(that.data.result.length+"张实际图片")
          var strify = JSON.stringify(res.delta);//dealta转成字符串变成strify
          console.log(strify);
          //提交审核
          //发布
          utils.addDB('Articles',{
            // 'articleID':'id' 文章ID
            'title':title, //标题
            'subTitle':subTitle, //子标题
            'images': that.data.result,//图片数组
            'content':res.delta,
            'time':time,// 发布时间
            'like':0,// 点赞数
            'discuss':0,// 评论数 
            'collect':0,// 收藏数
            'visibility': visible//可见性
          });
          wx.hideLoading({
            success: (res) => {
              console.log('文章发布成功')
            },
          })
          var arrParse = JSON.parse(strify);//strify转成数组变回dealta，这里的arrParse是等于dealta的
          console.log(arrParse);
        } else {
          // console.log(res.html)
          wx.showModal({
            showCancel: false,
            title: '提示',
            content: '内容不能为空或仅包含图片'
          })
          return;
        }
      }
    });


  },

  onUnload: function () {
    let that=this;
    that.editorCtx.getContents({
      success: res=>{
        // html=res.html;
        // text=res.text;
        let content=res;
        if (!res.text.replace(/\s+/g, '').length ==0) {//res.html!==constTxt内容不为空
        wx.showModal({
          title: '要放弃编辑的内容吗？',
          // cancelColor: '#000000',
          confirmColor:'#f00',
          success (res) {
            if (res.confirm) {
              console.log('用户点击确认');
              that.clear();
            } else if (res.cancel) {
              console.log('用户点击取消');
              getApp().globalData.article=content
              console.log(content)
            }
          }
        })
      }
      }
    });
    
  },
  //缩进
  indentClick(){
    this.editorCtx.insertText({
      text: "ㅤㅤ"
    })
  },
  retain() {
    this.$wuxBackdrop.retain()
    this.setData({
      locks: this.$wuxBackdrop.backdropHolds,
      show:true//显示组件
    })
  },
  release() {
    this.$wuxBackdrop.release()
    this.setData({
      locks: this.$wuxBackdrop.backdropHolds,
      show:false
    })
  }
})

